﻿using System;
using Microsoft.AspNetCore.Mvc;

namespace FlashPay.Admin.Controllers
{
    using FlashPay.Admin.ViewModels.Permission;
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request;
    using FlashPay.Entity.Request.Permission;
    using FlashPay.Entity.Response.Permission;
    using FlashPay.Entity.Response.User;
    using FlashPay.Service.Interface;
    using FlashPay.Util;
    using Microsoft.AspNetCore.Http;
    using Newtonsoft.Json;
    using System.Collections.Generic;
    using System.Linq;

    public class PermissionController : BaseController
    {
        #region 注入
        /// <summary>
        /// 功能权限业务接口
        /// </summary>
        private readonly PermissionService _permissionService;

        /// <summary>
        /// 日志权限业务接口
        /// </summary>
        private readonly LogService _logService;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="sysRoleService">功能权限业务接口</param>
        /// <param name="logService">日志权限业务接口</param>
        public PermissionController(IAuthenticate<TicketResponse> _manage, IHttpContextAccessor _accessor, PermissionService permissionService, LogService logService) : base(_manage, _accessor)
        {
            _permissionService = permissionService;
            _logService = logService;
        }
        #endregion

        /// <summary>
        /// 根据编号获取角色
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.Permission0001)]
        public JsonResult Get(int id)
        {
            //输出
            var response = new JResult<PermissionResponse>()
            {
                Success = false
            };

            var model = _permissionService.Get(id);
            if (model != null)
            {
                response.Data = model;
                response.Success = true;
            }
            return Json(response);
        }

        #region 新增、编辑
        /// <summary>
        /// 根据编号获取角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AuthorizeFilter(AuthCode.Permission0002, AuthCode.Permission0003,AuthCode.AllowEdit)]
        public JsonResult GetAddOrEdit(int? id)
        {
            //输出
            var response = new JResult<PermissionResponse>()
            {
                Success = false
            };

            if (id.HasValue)
            {
                var model = _permissionService.Get(id.Value);
                if (model != null)
                {
                    response.Data = model;
                    response.Success = true;
                }
            }
            return Json(response);
        }

        /// <summary>
        /// 功能权限保存或修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AuthorizeFilter(AuthCode.Permission0002, AuthCode.Permission0003)]
        public JsonResult SaveOrEdit(SaveOrEditPermissionViewModel permission)
        {
            if (!ModelState.IsValid)
            {
                var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();

                return Json(new JResult()
                {
                    Success = false,
                    ErrorMessage = message
                });
            }

            var permissionRequest = new PermissionRequest()
            {
                Pid = permission.Pid,
                PParent = permission.PParent,
                PName = permission.PName,
                PCode = permission.PCode,
                NodeType = this._manage.data.MType,
                SortNo = permission.SortNo,
                Hide = permission.Hide
            };
            //日志
            permissionRequest.Ip = HttpContext.GetUserIp();
            permissionRequest.CreateId = _manage.data.UserID;
            permissionRequest.CreateName = _manage.data.UserName;
            permissionRequest.CompanyId = _manage.data.CompanyID;
            permissionRequest.RequestUrl = HttpContext.Request.Host.ToString();
            permissionRequest.RequestData = JsonConvert.SerializeObject(permission);

            var response = _permissionService.SaveOrEdit(permissionRequest);
            return Json(response);
        }

        #endregion

        #region 权限名字搜索
        /// <summary>
        /// 权限名字搜索
        /// </summary>
        /// <param name="query">参数</param>
        [AuthorizeFilter(AuthCode.Permission0001)]
        public JsonResult PermissionAutoSearch(PermissionQuery query)
        {
            //输出
            var response = new JResult<List<PermissionResponse>>()
            {
                Success = true
            };

            try
            {
                query.PName = WebUtil.FilterChar(query.PName);
                query.PCode = WebUtil.FilterChar(query.PCode);
                query.NodeType = this._manage.data.MType;
                query.CurrentPageIndex = 1;
                query.PageSize = 10;


                var pager = _permissionService.GetPager(query);
                if (pager != null && pager.TData != null) {

                    var permissionResponses = new List<PermissionResponse>();

                    foreach (var item in pager.TData) {
                        permissionResponses.Add(new PermissionResponse() {
                            Pid = item.Pid,
                            PName = item.PName,
                            PCode = item.PCode
                        });
                    }

                    response.Data = permissionResponses;
                }
            }
            catch (Exception ex) {
                response.Success = false;
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }
        #endregion

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AuthorizeFilter(AuthCode.Permission0004)]
        public JsonResult UpdateStatus(UpdateStatusRequest request)
        {
            //输出
            var response = new JResult()
            {
                Success = false
            };
            //日志
            request.Ip = HttpContext.GetUserIp();
            request.CreateId = _manage.data.UserID;
            request.CreateName = _manage.data.UserName;
            request.CompanyId = _manage.data.CompanyID;
            request.RequestUrl = HttpContext.Request.Host.ToString();

            response = _permissionService.UpdateStatus(request);

            return Json(response);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<PermissionResponse></returns>
        [AuthorizeFilter(AuthCode.Permission0001)]
        public JsonResult GetPager(PermissionQuery query)
        {
            query.PName = WebUtil.FilterChar(query.PName);
            query.PCode = WebUtil.FilterChar(query.PCode);
            query.NodeType = this._manage.data.MType;
            var pager = _permissionService.GetPager(query);

            return Json(pager);
        }
    }
}
